package com.webserver.http;

import java.io.*;
import java.net.Socket;

public class HttpResponse {
    private String protocol = "HTTP/1.1";
    private String statusCode = "200";
    private String statusReson = "OK";
    private File entity;

    private Socket socket;
    public HttpResponse(Socket socket){
        this.socket = socket;
    }
    public void flush()throws IOException{
        sendStatusLine();
        sendHeaders();
        sendContent();
    }
    private void sendStatusLine()throws IOException{
        String line = protocol + " " + statusCode + " " + statusReson;
        println(line);
    }
    private void sendHeaders()throws IOException{
         String line = "Content-Type:text/html";
         println(line);

         line = "Content-Length:"+entity.length();
         println(line);

         //单独发送CRLF表示响应头发送完毕
         println("");
    }
    private void sendContent()throws IOException{
        OutputStream out = socket.getOutputStream();
        try(FileInputStream fis = new FileInputStream(entity);//从文件中获得输入字节
        ) {
            byte[] buf = new byte[1024 * 8];
            int len;
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
        }
    }
    public void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[]data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);
        out.write(10);
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReson() {
        return statusReson;
    }

    public void setStatusReson(String statusReson) {
        this.statusReson = statusReson;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }
}
